<template>
  <div class="login-container">
    <!-- 标题区域 -->
    <div class="login-header">
      <h1>电影售票系统</h1>
      <p>请输入手机号登录您的账户</p>
    </div>

    <!-- 表单区域 -->
    <div class="login-form">
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="phone">手机号</label>
          <input
            type="text"
            id="phone"
            placeholder="请输入11位手机号"
            v-model="telno"
            required
          />
          <span class="error-message" v-if="errors.phone">{{
            errors.phone
          }}</span>
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
            type="password"
            id="password"
            placeholder="请输入密码"
            v-model="password"
            required
          />
          <span class="error-message" v-if="errors.password">{{
            errors.password
          }}</span>
        </div>

        <button type="submit" class="login-btn" :disabled="isSubmitting">
          {{ isSubmitting ? "登录中..." : "登录" }}
        </button>
      </form>

      <!-- 操作链接区域 -->
      <div class="login-actions">
        <span>还没有账号？</span>
        <router-link to="/register" class="register-link">立即注册</router-link>
      </div>
    </div>
  </div>
</template>
<style scoped>
/* 整体容器：居中 + 限制宽度 + 上下留白 */
.login-container {
  max-width: 400px;
  margin: 60px auto; /* 水平居中，上下间距60px */
  padding: 0 20px; /* 左右内边距，适配小屏幕 */
}

/* 标题区域：居中 + 底部间距 */
.login-header {
  text-align: center;
  margin-bottom: 40px; /* 与表单区拉开距离 */
}

.login-header h1 {
  color: #a2131d; /* 主色调统一 */
  font-size: 28px;
  margin-bottom: 10px;
}

.login-header p {
  color: #666;
  font-size: 15px;
}

/* 表单组：统一间距 + 输入框样式 */
.form-group {
  margin-bottom: 25px; /* 每个表单项底部间距 */
}

.form-group label {
  display: block;
  margin-bottom: 8px; /* label与输入框间距 */
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 15px;
  transition: border-color 0.2s; /* 聚焦动画 */
}

.form-group input:focus {
  outline: none;
  border-color: #a2131d;
  box-shadow: 0 0 0 2px rgba(162, 19, 29, 0.1); /* 聚焦高亮 */
}

/* 登录按钮：全屏宽度 + 上下间距 */
.login-btn {
  width: 100%;
  padding: 12px;
  background-color: #a2131d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  margin-bottom: 20px; /* 与下方链接区拉开距离 */
  transition: background-color 0.2s; /* hover动画 */
}

.login-btn:hover:not(:disabled) {
  background-color: #8a1018; /*  hover深色反馈 */
}

.login-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 操作链接区域：居中 + 文字对齐 */
.login-actions {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.register-link {
  color: #a2131d;
  text-decoration: none;
  margin: 0 5px; /* 链接左右间距 */
}

/* 错误提示样式 */
.error-message {
  color: #a2131d;
  font-size: 12px;
  margin-top: 5px;
  display: block;
  min-height: 18px;
}
</style>
<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { login } from "@/api/user";
import { RouterLink } from "vue-router";
import { useUserStore } from "@/store";
const userStore = useUserStore();

// 表单数据
const telno = ref("");
const password = ref("");

// 状态管理
const errors = reactive({});
const isSubmitting = ref(false);
const router = useRouter();

// 验证表单
const validateForm = () => {
  let isValid = true;
  errors.phone = "";
  errors.password = "";

  // 手机号验证
  if (!telno.value) {
    errors.phone = "请输入手机号";
    isValid = false;
  } else if (!/^1[3-9]\d{9}$/.test(telno.value)) {
    errors.phone = "请输入正确的11位手机号";
    isValid = false;
  }

  // 密码验证
  if (!password.value) {
    errors.password = "请输入密码";
    isValid = false;
  } else if (password.value.length < 6 || password.value.length > 16) {
    errors.password = "密码长度应为6-16位";
    isValid = false;
  }

  return isValid;
};

const handleLogin = async () => {
  if (!validateForm()) return;

  try {
    isSubmitting.value = true;
    const res = await login({
      phone: telno.value,
      password: password.value,
    });

    console.log("完整登录响应:", res);
    console.log("登录响应数据:", res.data);

    // 处理响应数据
    let loginData = res.data;

    // 检查响应结构
    console.log("响应结构检查:", {
      hasData: !!loginData,
      hasNestedData: !!(loginData && loginData.data),
      code: loginData?.code,
      message: loginData?.message,
      token: loginData?.token,
      userId: loginData?.userId,
    });

    // 如果响应有嵌套的data字段，使用它
    if (loginData && loginData.data) {
      loginData = loginData.data;
      console.log("使用嵌套数据:", loginData);
    }

    // 检查登录是否成功
    if (loginData.code === 200) {
      const token = loginData.token;
      const userId = loginData.userId;
      const userName = telno.value;

      console.log("提取的用户信息:", {
        token: typeof token,
        tokenValue: token,
        userId: typeof userId,
        userIdValue: userId,
        userName,
      });

      // 验证数据是否存在
      if (!token) {
        throw new Error("Token 为空，无法保存");
      }
      if (!userId) {
        throw new Error("UserId 为空，无法保存");
      }

      // 保存到localStorage - 确保值是字符串
      localStorage.setItem("token", String(token));
      localStorage.setItem("userId", String(userId));
      localStorage.setItem("userName", userName);

      // 立即验证保存是否成功
      const savedToken = localStorage.getItem("token");
      const savedUserId = localStorage.getItem("userId");

      console.log("保存验证:", {
        savedToken: savedToken ? "成功" : "失败",
        savedTokenValue: savedToken,
        savedUserId: savedUserId ? "成功" : "失败",
        savedUserIdValue: savedUserId,
      });

      if (!savedToken || !savedUserId) {
        throw new Error("保存到 localStorage 失败");
      }

      // 强制更新用户状态
      userStore.updateLoginStatus();

      // 等待状态更新
      await new Promise((resolve) => setTimeout(resolve, 100));

      // 检查重定向路径
      const redirectPath = localStorage.getItem("redirectPath");
      const redirectQuery = localStorage.getItem("redirectQuery");

      console.log("重定向信息：", {
        redirectPath,
        redirectQuery,
      });

      let targetPath = "/reying";
      let targetQuery = {};

      if (redirectPath && redirectPath !== "/login") {
        localStorage.removeItem("redirectPath");
        localStorage.removeItem("redirectQuery");
        targetPath = redirectPath;
        targetQuery = redirectQuery ? JSON.parse(redirectQuery) : {};
      }

      console.log("准备跳转到：", targetPath);

      // 直接跳转
      router.push({
        path: targetPath,
        query: targetQuery,
      });
    } else {
      alert(loginData.message || "登录失败，请重试");
    }
  } catch (err) {
    console.error("登录失败", err);
    const errorMsg =
      err.message || err.response?.data?.message || "网络错误，登录失败";
    alert(errorMsg);
  } finally {
    isSubmitting.value = false;
  }
};
</script>
